package com.example.mysimpleexample.fragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.mysimpleexample.R;
import com.example.mysimpleexample.entity.NewsType;
import com.example.mysimpleexample.util.Constants;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.base.XPageFragment;
import com.xuexiang.xui.adapter.FragmentAdapter;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.widget.tabbar.EasyIndicator;
import com.xuexiang.xui.widget.tabbar.TabSegment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@Page(name = "指示器")
public class EasyIndicatorFragment extends XPageFragment {
    @BindView(R.id.tabSegment)
    TabSegment tabSegment;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    private List<NewsType> newsTypes;
    public static final String newTypeUrl = "/news/types";
    private FragmentAdapter<Fragment> adapter;
    private OkHttpClient okHttpClient = new OkHttpClient();
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int what = msg.what;
            switch (what) {
                case 0x001:
                    newsTypes = (List<NewsType>) msg.obj;
                    String[] titles = new String[newsTypes.size()];
                    for (NewsType newsType : newsTypes) {
                        tabSegment.addTab(new TabSegment.Tab(newsType.getTypeName()));
                        adapter.addFragment(new SimpleListFragment().newInstance(newsType.getTypeName(),newsType.getTypeId()),newsType.getTypeName());
                    }
                    viewPager.setAdapter(adapter);
                    /*viewPager.setCurrentItem(0,false);*/
                    viewPager.setOffscreenPageLimit(1);
                    break;
            }
            return true;
        }
    });

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_segment;
    }

    @Override
    protected void initViews() {
        adapter = new FragmentAdapter<>(getChildFragmentManager());

        int space = DensityUtils.dp2px(getContext(),16);
        tabSegment.setHasIndicator(true);
        tabSegment.setMode(TabSegment.MODE_SCROLLABLE);
        tabSegment.setItemSpaceInScrollMode(space);
        tabSegment.setPadding(space,0,space,0);
        tabSegment.setupWithViewPager(viewPager,false);
        getNewsType();
    }

    @Override
    protected void initListeners() {

    }

    @Override
    protected void initArgs() {

    }

    private void getNewsType(){
        Request request = new Request.Builder()
                .url(Constants.BASE_URL.concat(newTypeUrl))
                .addHeader("app_id",Constants.APP_ID)
                .addHeader("app_secret",Constants.APP_SECRET)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        String responseText = response.body().string();
                        JSONObject jsonObject = JSONObject.parseObject(responseText);
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        newsTypes = new ArrayList<>();
                        for (Object o : jsonArray) {
                            NewsType newsType = JSONObject.parseObject(o.toString(),NewsType.class);
                            newsTypes.add(newsType);

                        }
                        Message message = Message.obtain();
                        message.what = 0x001;
                        message.obj = newsTypes;
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }
}
